import 'dart:io';
import 'dart:typed_data';

import 'package:path_provider/path_provider.dart';

import 'log_util.dart';

class FileUtil {
  static const String DirectoryImage = "/images";

  static const String DirectoryFile = "/files";

  static const String DirectoryTemporary = '/Temporary';

  static Future<String> createFileToTemporaryDirectory(Uint8List uint8list,
      {String? fileName}) async {
    String name = fileName == null
        ? DateTime.now().millisecondsSinceEpoch.toString()
        : fileName;

    String dirPath = await getDataPathOfDirectory(DirectoryTemporary);
    File imageFile = File("$dirPath/$name.png");
    imageFile.createSync(recursive: true);
    imageFile.writeAsBytesSync(uint8list);
    return imageFile.path;
  }

  /// 递归方式 计算文件的大小
  static Future<double> getTotalSizeOfFilesInDir(
      final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      LogUtil.e('get total size of files in dir error: $e');
      return 0;
    }
  }

  ///递归方式删除目录
  static Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      LogUtil.e('delete dir error: $e');
    }
  }

  /// 根据传入的文件夹获取存放数据的路径
  ///
  /// directory 文件夹('/images','/files',etc.)
  static Future<String> getDataPathOfDirectory(String directory) async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    Directory dir = Directory(documentsDirectory.path + directory);

    if (!await dir.exists()) dir.createSync(recursive: true);

    return dir.path;
  }

  /// 根据传入的文件夹路径获取内部存储器的路径
  ///
  /// directory 文件夹('/images','/files',etc.)
  static Future<String> getInternalPathOfDirectory(String directory) async {
    Directory supportDir = await getApplicationSupportDirectory();
    Directory dir = Directory(supportDir.path + directory);

    if (!await dir.exists()) dir.createSync(recursive: true);

    return dir.path;
  }
}
